﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PMSGSC.DAL;
using PMSGSC.BLL;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraRichEdit;
using DevExpress.XtraPrinting;

namespace PMSGSC.App
{
    public partial class frmStockItem : DevExpress.XtraEditors.XtraForm
    {
        public frmStockItem(List<PartsInEquipment> partList, frmMain main)
        {
            InitializeComponent();
            partsInEquipmentBindingSource.DataSource = partList;
            stockUnitBindingSource.DataSource = Unit_BLL.GetAll(frmMain.ship.Ship_ID);
            stockBindingSource.DataSource = Stock_BLL.GetAll(frmMain.ship.Ship_ID);
            objMain = main;
        }
        private frmMain objMain;
        private PartsInEquipment part;
        private void SetValueBeforeInsert()
        {
            if (drawingNoTextEdit.ContainsFocus)
                part.DrawingNo = drawingNoTextEdit.Text;

            if (ucRichEditControl1.isChange)
                part.Note = ucRichEditControl1.richEditControl1.Text;

            if (minTextBox.ContainsFocus && minTextBox.Text != "")
                part.Min = int.Parse(minTextBox.Text);
            
            if (maxTextBox.ContainsFocus && maxTextBox.Text != "")
                part.Max = int.Parse(maxTextBox.Text);
                
            if (stockUnit_IDGridLookUpEdit.ContainsFocus && stockUnit_IDGridLookUpEdit.Text != "")
                part.StockUnit_ID = int.Parse((stockUnit_IDGridLookUpEdit.EditValue.ToString()));

            if (ucLoadMaker1.lb_id.Text != "")
                part.Maker = BaseDAL.DB.Makers.Single(c => c.Maker_ID == int.Parse(ucLoadMaker1.lb_id.Text));

            if (ucLoadVendor1.lbid.Text != "")
                part.Vendor = BaseDAL.DB.Vendors.Single(c => c.Vendor_ID == int.Parse(ucLoadVendor1.lbid.Text));

            part.InStock = int.Parse(lbTotalStock.Text);
            ucRichEditControl1.isChange = false;
        }

        private void partsInpartmentBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            if (part != null)
            {
                if (ucLoadMaker1.isChanges || ucLoadVendor1.isChanges || ucLoadPartInEquipment1.isChanges || ucRichEditControl1.isChange)
                {
                    if (ucLoadMaker1.lb_id.Text != "")
                        part.Maker = BaseDAL.DB.Makers.Single(c => c.Maker_ID == int.Parse(ucLoadMaker1.lb_id.Text));

                    if (ucLoadVendor1.lbid.Text != "")
                        part.Vendor = BaseDAL.DB.Vendors.Single(c => c.Vendor_ID == int.Parse(ucLoadVendor1.lbid.Text));

                    if (ucLoadPartInEquipment1.lbid.Text != "")
                    {
                        part.PartCode = ucLoadPartInEquipment1.txtCode.Text;
                        part.PartName = ucLoadPartInEquipment1.txtName.Text;
                    }

                    part.Note = ucRichEditControl1.richEditControl1.Text;
                    ucLoadMaker1.isChanges = false;
                    ucLoadVendor1.isChanges = false;
                    ucRichEditControl1.isChange = false;
                    ucLoadPartInEquipment1.isChanges = false;
                }
            }

            part = partsInEquipmentBindingSource.Current as PartsInEquipment;
            if (part != null)
            {
                ucRichEditControl1.richEditControl1.Text = part.Note;
                ucLoadMaker1.SetValue(part.Maker.CodeMaker, part.Maker.NameMaker, part.Maker_ID.ToString());
                ucLoadVendor1.SetValue(part.Vendor.CodeVendor, part.Vendor.NameVendor, part.Vendor_ID.ToString());
                ucLoadPartInEquipment1.SetValue(part.PartCode, part.PartName, part.Parts_ID.ToString());
                locationInStockBindingSource.DataSource =  LocationInStock_BLL.GetDataByPartId(part.Parts_ID, false);
                int stockTotal = 0;
                foreach (LocationInStock location in locationInStockBindingSource.Cast<LocationInStock>().ToList())
                {
                    stockTotal += location.Quantity.Value;
                }
                lbTotalStock.Text = stockTotal.ToString();
            }
            SetValueBeforeInsert();
        }

        private void stockUnit_IDGridLookUpEdit_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (e.NewValue == null)
                part.StockUnit = null;
            else
                part.StockUnit = BaseDAL.DB.StockUnits.Single(n => n.StockUnit_ID == (int)e.NewValue);
        }

        private void btnSaveAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SetValueBeforeInsert();
            foreach (PartsInEquipment part in partsInEquipmentBindingSource.Cast<PartsInEquipment>().ToList())
            {
                PartInEquipment_BLL.Update(part);
            }
        }
        public List<PartsInEquipment> GetNumberOfJobBeforePrint()
        {
            List<PartsInEquipment> partList = new List<PartsInEquipment>();
            foreach (PartsInEquipment p in partsInEquipmentBindingSource.Cast<PartsInEquipment>().ToList())
            {
                if (p.IsCheck.Value)
                    partList.Add(p);
            }
            return partList;
        }

        private void repositoryItemCheckEdit1_CheckedChanged(object sender, EventArgs e)
        {
            part.IsCheck = bool.Parse(repositoryItemCheckEdit1.ValueChecked.ToString());
        }

        private void btnPrints_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            List<PartsInEquipment> partList = GetNumberOfJobBeforePrint();
            if (partList.Count > 0)
            {
                frmReviewPart printPart = new frmReviewPart(partList);
                printPart.MdiParent = objMain;
                printPart.Show();
            }
        }

        #region Location
        // Khai báo trạng thái mặc định 
        private Status statusPartJob = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private LocationInStock location = new LocationInStock();
        
        //Hiển thị số thứ tự của gridview
        private void gridViewPJ_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        // Sự kiện cập nhật dữ liệu xuống database
        private void gridViewPJ_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SavePartJobToDatabase();
        }
        private void SavePartJobToDatabase()
        {
              if (statusPartJob == Status.Update)
                {
                    if (XtraMessageBox.Show("Do you want to save changes?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        
                        bool result = LocationInStock_BLL.Update(location);
                        if (!result)
                        {
                            XtraMessageBox.Show("Update Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }

                    locationInStockBindingSource.DataSource =  LocationInStock_BLL.GetDataByPartId(part.Parts_ID, true);
                }
                if (statusPartJob == Status.New)
                {
                    bool result = LocationInStock_BLL.Insert(location);
                    if (!result)
                    {
                        XtraMessageBox.Show("Insert Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    statusPartJob = Status.Update;
                }
        }
        private void txtQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private static void OnlyInputNumberic(KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }

        private void DeletePartJob(NavigatorButtonClickEventArgs e)
        {
            if (location != null && LocationInStock_BLL.isExits(location))
            {
                bool result = LocationInStock_BLL.Delete(location);
                if (!result)
                {
                    XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                locationInStockBindingSource.DataSource = LocationInStock_BLL.GetDataByPartId(part.Parts_ID, true);
            }
            else
            {
                locationInStockBindingSource.RemoveCurrent();
            }
            e.Handled = true;
        }

        // Sự kiện nhân phím delete sảy ra
        private void gridViewPJ_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {

                if (location != null && LocationInStock_BLL.isExits(location))
                {
                    bool result = LocationInStock_BLL.Delete(location);
                    if (!result)
                    {
                        XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    locationInStockBindingSource.DataSource = LocationInStock_BLL.GetDataByPartId(part.Parts_ID, true);
                }
                else
                {
                    locationInStockBindingSource.RemoveCurrent();
                }
                e.Handled = true;
            }
        }

        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewPJ_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            statusPartJob = Status.New;
            GridView view = (GridView)sender;

            GridColumn Quantity = view.Columns["Quantity"];
            view.SetRowCellValue(e.RowHandle, Quantity, 0);
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewPJ_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (null != location)
            {
                GridView view = (GridView)sender;
                GridColumn StockID = view.Columns["Stock_ID"];
                if (null == view.GetRowCellValue(e.RowHandle, StockID))
                {
                    e.Valid = false;
                    view.FocusedColumn = StockID;
                    e.ErrorText = "Please enter the Stock ";
                    view.SetColumnError(StockID, "Stock is not empty");
                }
                location = locationInStockBindingSource.Current as LocationInStock;
                location.Parts_ID = part.Parts_ID;
                if (LocationInStock_BLL.isExits(location) && statusPartJob != Status.Update)
                {
                    e.Valid = false;
                    view.FocusedColumn = StockID;
                    e.ErrorText = "Part is exits. ";
                    view.SetColumnError(StockID, "Part is exits");
                }
            }
        }
        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewPJ_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(locationInStockGridControl.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    locationInStockBindingSource.DataSource = LocationInStock_BLL.GetDataByPartId(part.Parts_ID, true);
                    statusPartJob = Status.Update;
                }
            }

        }
        // Đặt lại trạng thái update 
        private void gridViewPJ_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusPartJob = Status.Update;
            }
        }

        #endregion

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle != GridControl.NewItemRowHandle)
                repositoryItemGridLookUpEdit1.ReadOnly = true;
            else
                repositoryItemGridLookUpEdit1.ReadOnly = false;
        }

        private void locationInStockBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            location = locationInStockBindingSource.Current as LocationInStock;
        }

        private void repositoryItemGridLookUpEdit1_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((LocationInStock)gridView1.GetFocusedRow()).Stock = null;
            else
                ((LocationInStock)gridView1.GetFocusedRow()).Stock = BaseDAL.DB.Stocks.Single(n => n.Stock_ID == (int)e.NewValue);
        }

        private void gridView2_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gridView2_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView view = sender as GridView;
            GridColumn IsCheckCol = view.Columns["IsCheck"];
            if (!view.IsNewItemRow(view.FocusedRowHandle) && view.FocusedColumn != IsCheckCol)
                e.Cancel = true;
        }
        private void locationInStockGridControl_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.CancelEdit:
                    DeletePartJob(e);
                    break;
            }
        }

        private void minTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void maxTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            XtraMessageBox.Show("This fuction building !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}